<?php
declare(strict_types=1);
namespace Aincrid\MySwoole;

use Aincrid\MySwoole\Response\JsonResponse;
use Swoole\Http\Response as SwooleResponse;

class Response
{
    protected ?SwooleResponse $response = null;

    protected int $httpCode;

    protected string|array $data;

    public function __construct(SwooleResponse $response)
    {
        $this->response = $response;
    }


    public function redirect(string $url)
    {
        $this->response->redirect($url);
    }


    public function json(array $data, int $httpCode = 200): JsonResponse
    {
        return $this->response($data, $httpCode);
    }

    public function html(string $data, int $httpCode = 200)
    {
        return $this->response($data, $httpCode, 'html');
    }


    public function setHeader(string $key, string $value)
    {
        $this->response->header($key, $value);
    }


    public function setData(array|string $data)
    {
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }

    public function setHttpCode(int $httpCode)
    {
        $this->httpCode = $httpCode;
    }

    public function getHttpCode()
    {
        return $this->httpCode;
    }

    public function response(string|array $data, int $httpCode, $type = 'json'): Response
    {
        $response = new ('Aincrid\MySwoole\Response\\' . ucfirst($type) . 'Response')($this->response);
        $response->setHeader('Content-Type', 'text/' . $type . ';charset=utf-8');
        $response->setHttpCode($httpCode);
        $response->setData($data);
        return $response;
    }



    public function httpNotFound()
    {
        $this->response('NOT FOUND', 404, 'html');
    }
}